#include "../includes/DiskDriver.h"
#include "../includes/DiskManager.h"
#include <iostream>
#include <string>
#include <vector>

// 测试代码
void test_write_read() {
    DiskDriver& driver = DiskDriver::getInstance("../disk_file");
    
    DiskManager::Inode inode1, inode2;
    inode1.id = 1;
    strcpy(inode1.path, "file1.txt");
    inode1.size = 100;
    
    inode2.id = 2;
    strcpy(inode2.path, "file2.txt");
    inode2.size = 200;
    
    off_t offset1 = 420;
    off_t offset2 = 1584;
    
    std::cout << "写入inode1到偏移 " << offset1 << std::endl;
    ssize_t result1 = driver.d_write(&inode1, sizeof(inode1), offset1);
    std::cout << "写入结果: " << result1 << std::endl;
    
    std::cout << "写入inode2到偏移 " << offset2 << std::endl;
    ssize_t result2 = driver.d_write(&inode2, sizeof(inode2), offset2);
    std::cout << "写入结果: " << result2 << std::endl;
    
    // 读取验证
    DiskManager::Inode read_inode1;
    ssize_t read_result = driver.d_read(&read_inode1, sizeof(read_inode1), offset1);
    std::cout << "从偏移 " << offset1 << " 读取结果: " << read_result << std::endl;
    std::cout << "读取到的ID: " << read_inode1.id << ", 路径: " << read_inode1.path << std::endl;
}

void test_inode_set_multiple() {
    std::string disk_path = "../disk_file";
    
    // 获取DiskManager实例
    DiskManager& disk_manager = DiskManager::getInstance(disk_path);
    
    // 确保超级块已初始化
    disk_manager.super_block_clear();
    
    std::cout << "=== 测试多次调用inode_set() ===" << std::endl;
    
    // DiskDriver用于直接读取验证
    DiskDriver& disk_driver = DiskDriver::getInstance(disk_path);
    
    for (int i = 0; i <= 3; ++i) {
        std::cout << "\n--- 插入ID为 " << i << " 的inode ---" << std::endl;
        
        // 创建测试inode
        DiskManager::Inode test_inode;
        test_inode.id = i;
        test_inode.size = (i + 1) * 100;  // 不同的大小
        test_inode.block_num = 0;  // 初始块数为0
        
        // 设置不同的文件名
        std::string filename = "test_file_" + std::to_string(i) + ".txt";
        strncpy(test_inode.path, filename.c_str(), sizeof(test_inode.path) - 1);
        test_inode.path[sizeof(test_inode.path) - 1] = '\0';
        
        // 初始化blocks数组
        for (int j = 0; j < BLOCKS_NUM; ++j) {
            test_inode.blocks[j] = -1;
        }
        
        std::cout << "准备写入 - ID: " << test_inode.id 
                  << ", 路径: " << test_inode.path 
                  << ", 大小: " << test_inode.size << std::endl;
        
        // 调用inode_set
        int result = disk_manager.inode_set(i, test_inode);
        std::cout << "inode_set() 返回值: " << result << std::endl;
        
        // 读取位置420处的数据（ID为0的inode）
        DiskManager::Inode inode_at_420;
        ssize_t read_result = disk_driver.d_read(&inode_at_420, sizeof(inode_at_420), 420);
        
        std::cout << "从偏移420读取结果: " << read_result << std::endl;
        if (read_result == sizeof(inode_at_420)) {
            std::cout << "420处的inode - ID: " << inode_at_420.id 
                      << ", 路径: " << inode_at_420.path 
                      << ", 大小: " << inode_at_420.size << std::endl;
        } else {
            std::cout << "从偏移420读取失败" << std::endl;
        }
    }
    
    std::cout << "\n=== 最终验证 ===" << std::endl;
    
    // 最后再次读取420处的数据
    DiskManager::Inode final_check;
    ssize_t final_read = disk_driver.d_read(&final_check, sizeof(final_check), 420);
    std::cout << "最终从偏移420读取: " << final_read << std::endl;
    if (final_read == sizeof(final_check)) {
        std::cout << "420处最终数据 - ID: " << final_check.id 
                  << ", 路径: " << final_check.path 
                  << ", 大小: " << final_check.size << std::endl;
    }
}

void test_inode_set_multiple2() {
    std::string disk_path = "../disk_file";
    
    // 获取DiskManager实例
    DiskManager& disk_manager = DiskManager::getInstance(disk_path);
    
    // 确保超级块已初始化
    disk_manager.super_block_clear();
    
    std::cout << "=== 测试多次调用inode_set() ===" << std::endl;
    
    for (int i = 0; i <= 3; ++i) {
        std::cout << "\n--- 插入ID为 " << i << " 的inode ---" << std::endl;
        
        // 创建测试inode
        DiskManager::Inode test_inode;
        test_inode.id = i;
        test_inode.size = (i + 1) * 100;  // 不同的大小
        test_inode.block_num = 0;  // 初始块数为0
        
        // 设置不同的文件名
        std::string filename = "test_file_" + std::to_string(i) + ".txt";
        strncpy(test_inode.path, filename.c_str(), sizeof(test_inode.path) - 1);
        test_inode.path[sizeof(test_inode.path) - 1] = '\0';
        
        // 初始化blocks数组
        for (int j = 0; j < BLOCKS_NUM; ++j) {
            test_inode.blocks[j] = -1;
        }
        
        std::cout << "准备写入 - ID: " << test_inode.id 
                  << ", 路径: " << test_inode.path 
                  << ", 大小: " << test_inode.size << std::endl;
        
        // 调用inode_set
        int result = disk_manager.inode_set(i, test_inode);
        std::cout << "inode_set() 返回值: " << result << std::endl;
        
        // 使用DiskManager::inode_get()读取ID为0的inode（偏移420处）
        DiskManager::Inode inode_at_420;
        int get_result = disk_manager.inode_get(0, inode_at_420);
        
        std::cout << "从ID 0读取结果: " << get_result << std::endl;
        if (get_result != -1) {
            std::cout << "ID 0的inode - ID: " << inode_at_420.id 
                      << ", 路径: " << inode_at_420.path 
                      << ", 大小: " << inode_at_420.size << std::endl;
        } else {
            std::cout << "从ID 0读取失败" << std::endl;
        }
    }
    
    std::cout << "\n=== 最终验证 ===" << std::endl;
    
    // 最后再次读取ID为0的inode
    DiskManager::Inode final_check;
    int final_get = disk_manager.inode_get(0, final_check);
    std::cout << "最终从ID 0读取: " << final_get << std::endl;
    if (final_get != -1) {
        std::cout << "ID 0最终数据 - ID: " << final_check.id 
                  << ", 路径: " << final_check.path 
                  << ", 大小: " << final_check.size << std::endl;
    }
    
    // 验证所有写入的inode
    std::cout << "\n=== 验证所有写入的inode ===" << std::endl;
    for (int i = 0; i <= 3; ++i) {
        DiskManager::Inode verify_inode;
        int get_result = disk_manager.inode_get(i, verify_inode);
        std::cout << "ID " << i << " 读取结果: " << get_result;
        if (get_result != -1) {
            std::cout << " - 路径: " << verify_inode.path 
                     << ", 大小: " << verify_inode.size;
        }
        std::cout << std::endl;
    }
}

void test_new_inode_multiple() {
    std::string disk_path = "../disk_file";
    
    // 获取DiskManager实例
    DiskManager& disk_manager = DiskManager::getInstance(disk_path);
    
    // 确保超级块已初始化
    disk_manager.super_block_clear();
    
    std::cout << "=== 测试多次调用new_inode() ===" << std::endl;
    
    // 测试文件路径列表
    std::vector<std::string> test_paths = {
        "file_0.txt",
        "file_1.txt", 
        "file_2.txt",
        "file_3.txt"
    };
    
    std::vector<int> created_ids;  // 存储创建的inode ID
    
    for (size_t i = 0; i < test_paths.size(); ++i) {
        std::cout << "\n--- 创建文件: " << test_paths[i] << " ---" << std::endl;
        
        // 调用new_inode创建inode
        int id = disk_manager.new_inode(test_paths[i]);
        
        std::cout << "new_inode() 返回值: " << id << std::endl;
        
        if (id != -1) {
            created_ids.push_back(id);
            std::cout << "成功创建inode，ID: " << id << std::endl;
            
            // 验证创建的inode信息
            DiskManager::Inode created_inode;
            int get_result = disk_manager.inode_get(id, created_inode);
            std::cout << "验证创建结果 - 读取ID " << id << " 结果: " << get_result << std::endl;
            if (get_result != -1) {
                std::cout << "验证数据 - ID: " << created_inode.id 
                          << ", 路径: " << created_inode.path 
                          << ", 大小: " << created_inode.size << std::endl;
            }
        } else {
            std::cout << "创建inode失败" << std::endl;
        }
        
        // 检查ID为0的inode（偏移420处）是否仍然存在
        DiskManager::Inode inode_at_0;
        int check_result = disk_manager.inode_get(0, inode_at_0);
        
        std::cout << "从ID 0读取结果: " << check_result << std::endl;
        if (check_result != -1) {
            std::cout << "ID 0的inode - ID: " << inode_at_0.id 
                      << ", 路径: " << inode_at_0.path 
                      << ", 大小: " << inode_at_0.size << std::endl;
        } else {
            std::cout << "从ID 0读取失败（可能是ID 0还未创建）" << std::endl;
        }
    }
    
    std::cout << "\n=== 最终验证 ===" << std::endl;
    
    // 最后检查ID为0的inode
    DiskManager::Inode final_check;
    int final_get = disk_manager.inode_get(0, final_check);
    std::cout << "最终从ID 0读取: " << final_get << std::endl;
    if (final_get != -1) {
        std::cout << "ID 0最终数据 - ID: " << final_check.id 
                  << ", 路径: " << final_check.path 
                  << ", 大小: " << final_check.size << std::endl;
    }
    
    // 验证所有创建的inode
    std::cout << "\n=== 验证所有创建的inode ===" << std::endl;
    for (int id : created_ids) {
        DiskManager::Inode verify_inode;
        int get_result = disk_manager.inode_get(id, verify_inode);
        std::cout << "ID " << id << " 读取结果: " << get_result;
        if (get_result != -1) {
            std::cout << " - 路径: " << verify_inode.path 
                     << ", 大小: " << verify_inode.size;
        }
        std::cout << std::endl;
    }
    
    // 检查超级块状态
    std::cout << "\n=== 超级块状态 ===" << std::endl;
    DiskManager::SuperBlock current_super_block;
    int super_result = disk_manager.super_block_load(current_super_block);
    std::cout << "加载超级块结果: " << super_result << std::endl;
    
    int used_count = 0;
    for (int i = 0; i < INODE_NUM && i < 10; ++i) {  // 只显示前10个状态
        if (current_super_block.inode_state[i]) {
            used_count++;
            std::cout << "ID " << i << ": 已分配" << std::endl;
        }
    }
    std::cout << "前10个inode中已分配数量: " << used_count << std::endl;
}

int main(){
    // test_inode_set_multiple2();
    // test_new_inode_multiple();
    // // test_write_read();
    std::string path = "../disk_file";
    DiskManager& disk_manager = DiskManager::getInstance(path);
    
    // 初始化超级块
    disk_manager.super_block_clear();
    DiskManager::SuperBlock super_block;
    disk_manager.super_block_load(super_block);
    std::cout << "初始超级块信息:" << std::endl;
    std::cout << "inode_start: " << super_block.inode_start << std::endl;
    std::cout << "data_start: " << super_block.data_start << std::endl;
    
    // 测试inode创建
    std::cout << "\n=== 测试inode创建 ===" << std::endl;
    std::vector<int> created_ids;
    
    // 创建多个inode
    std::vector<std::string> test_files = {"test1.txt", "test2.txt", "test3.txt", "document.pdf", "image.jpg"};
    
    for (const auto& filename : test_files) {
        int id = disk_manager.new_inode(filename);
        if (id != -1) {
            created_ids.push_back(id);
            std::cout << "创建文件 '" << filename << "' 成功，ID: " << id << std::endl;
            
            // 验证创建的inode
            DiskManager::Inode inode;
            DiskDriver &disk_driver = DiskDriver::getInstance();
            disk_driver.d_read(&inode, sizeof(inode), 420);
            std::cout << "  验证 - ID: " << inode.id << ", 路径: " << inode.path 
            << ", 大小: " << inode.size << std::endl;
            if (disk_manager.inode_get(id, inode) != -1) {
                std::cout << "  验证 - ID: " << inode.id << ", 路径: " << inode.path 
                         << ", 大小: " << inode.size << std::endl;
            }
        } else {
            std::cout << "创建文件 '" << filename << "' 失败" << std::endl;
        }
    }
    
    // 测试根据路径查找inode
    std::cout << "\n=== 测试根据路径查找inode ===" << std::endl;
    for (const auto& filename : test_files) {
        DiskManager::Inode inode;
        if (disk_manager.inode_get(filename, inode) != -1) {
            std::cout << "找到文件 '" << filename << "', ID: " << inode.id 
                     << ", 大小: " << inode.size << std::endl;
        } else {
            std::cout << "未找到文件 '" << filename << "'" << std::endl;
        }
    }
    
    // 测试根据ID查找inode
    std::cout << "\n=== 测试根据ID查找inode ===" << std::endl;
    for (int id : created_ids) {
        DiskManager::Inode inode;
        if (disk_manager.inode_get(id, inode) != -1) {
            std::cout << "ID " << id << " 对应文件: " << inode.path << std::endl;
        } else {
            std::cout << "未找到ID为 " << id << " 的inode" << std::endl;
        }
    }
    
    // 测试修改inode
    std::cout << "\n=== 测试修改inode ===" << std::endl;
    if (!created_ids.empty()) {
        int test_id = created_ids[0];
        DiskManager::Inode inode;
        
        // 先获取原inode
        if (disk_manager.inode_get(test_id, inode) != -1) {
            std::cout << "修改前 - ID: " << inode.id << ", 路径: " << inode.path 
                     << ", 大小: " << inode.size << std::endl;
            
            // 修改inode信息
            inode.size = 1024;  // 设置文件大小为1024字节
            
            // 更新inode
            if (disk_manager.inode_set(test_id, inode) != -1) {
                std::cout << "修改inode " << test_id << " 成功" << std::endl;
                
                // 验证修改结果
                DiskManager::Inode updated_inode;
                if (disk_manager.inode_get(test_id, updated_inode) != -1) {
                    std::cout << "修改后 - ID: " << updated_inode.id 
                             << ", 路径: " << updated_inode.path 
                             << ", 大小: " << updated_inode.size << std::endl;
                }
            } else {
                std::cout << "修改inode " << test_id << " 失败" << std::endl;
            }
        }
    }
    
    // 测试删除inode（删除部分文件）
    std::cout << "\n=== 测试删除inode ===" << std::endl;
    if (created_ids.size() >= 2) {
        int id_to_delete = created_ids[0];
        std::string file_to_delete = test_files[0];
        
        // 删除前验证存在
        DiskManager::Inode inode_before;
        if (disk_manager.inode_get(id_to_delete, inode_before) != -1) {
            std::cout << "删除前 - 找到文件 '" << file_to_delete << "', ID: " << id_to_delete << std::endl;
        }
        
        // 根据ID删除
        if (disk_manager.inode_del(id_to_delete) != -1) {
            std::cout << "根据ID删除文件成功: " << id_to_delete << std::endl;
            
            // 验证删除结果
            DiskManager::Inode inode_after;
            if (disk_manager.inode_get(id_to_delete, inode_after) == -1) {
                std::cout << "验证: ID " << id_to_delete << " 的inode已不存在" << std::endl;
            } else {
                std::cout << "错误: ID " << id_to_delete << " 的inode仍然存在" << std::endl;
            }
            
            // 尝试根据路径删除（应该失败，因为已经删除）
            if (disk_manager.inode_del(file_to_delete) == -1) {
                std::cout << "根据路径删除已删除的文件失败（预期行为）" << std::endl;
            }
        } else {
            std::cout << "删除inode失败: " << id_to_delete << std::endl;
        }
        
        // 删除另一个文件，但这次使用路径删除
        if (created_ids.size() >= 2) {
            int id2_to_delete = created_ids[1];
            std::string file2_to_delete = test_files[1];
            
            if (disk_manager.inode_del(file2_to_delete) != -1) {
                std::cout << "根据路径删除文件成功: " << file2_to_delete << std::endl;
                
                // 验证删除结果
                DiskManager::Inode inode_after;
                if (disk_manager.inode_get(file2_to_delete, inode_after) == -1) {
                    std::cout << "验证: 文件 '" << file2_to_delete << "' 已不存在" << std::endl;
                }
            } else {
                std::cout << "根据路径删除文件失败: " << file2_to_delete << std::endl;
            }
        }
    }
    
    // 测试查找剩余的inode
    std::cout << "\n=== 测试剩余inode ===" << std::endl;
    for (size_t i = 2; i < created_ids.size(); ++i) {  // 跳过已删除的
        DiskManager::Inode inode;
        if (disk_manager.inode_get(created_ids[i], inode) != -1) {
            std::cout << "剩余文件 - ID: " << inode.id << ", 路径: " << inode.path << std::endl;
        }
    }
    
    // 再次加载超级块查看状态变化
    std::cout << "\n=== 最终超级块状态 ===" << std::endl;
    DiskManager::SuperBlock final_super_block;
    disk_manager.super_block_load(final_super_block);
    std::cout << "inode_start: " << final_super_block.inode_start << std::endl;
    std::cout << "data_start: " << final_super_block.data_start << std::endl;
    
    std::cout << "\n测试完成！" << std::endl;
    return 0;
}